package com.coding.service.impl;

import com.coding.config.LiveClientConfig;
import com.coding.dto.RestBean;
import com.coding.mapper.LiveMapper;
import com.coding.pojo.LiveInfo;
import com.coding.service.LiveService;
import com.coding.utils.AliyunOSSUtil;
import com.coding.utils.Constant;
import com.coding.utils.Create_Live_Url;
import com.coding.utils.LiveUtil;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class LiveServiceImpl implements LiveService {

    @Autowired
    private LiveMapper liveMapper;
    @Autowired
    private LiveClientConfig liveClientConfig;
    @Autowired
    private Create_Live_Url createLiveUrl;
    @Resource
    private RedisTemplate<String, Object> MyRedisTemplate;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private LiveUtil liveUtil;
    @Override
    public RestBean createLiveRoom(String userId, String title, MultipartFile coverImage) {
        System.out.println("userId = " + userId);
        System.out.println("title = " + title);
        System.out.println("coverImage = " + coverImage);




        // 先到 Redis 查看直播地址集合是否有这个直播间的播放地址
//        if (Boolean.TRUE.equals(MyRedisTemplate.hasKey(liveRoomKey))) {
//            // 如果存在，则返回直播间播放地址
//            Map<Object, Object> roomInfo = MyRedisTemplate.opsForHash().entries(liveRoomKey);
//            String pushUrl = (String) roomInfo.get("pushUrl");
//            return RestBean.success("已有创建直播间", pushUrl);
//        }

        // 如果不存在，则创建直播间
        liveClientConfig.setStreamName(userId);

        // 生成推流和拉流地址
        String pushUrl = createLiveUrl.generate_push_url(liveClientConfig.getPushDomain(), liveClientConfig.getPushKey(), liveClientConfig.getAppName(),
                liveClientConfig.getStreamName(), liveClientConfig.getExpireTime());
        String pullUrl = createLiveUrl.general_pull_url(liveClientConfig.getPullDomain(), liveClientConfig.getPullKey(), liveClientConfig.getAppName(), liveClientConfig.getStreamName(),
                liveClientConfig.getExpireTime());
        LiveInfo liveInfo = new LiveInfo();
        liveInfo.setPushUrl(pushUrl);
        liveInfo.setUserId(userId);
        liveInfo.setTitle(title);

        //直播间信息插入Mysql数据库
        liveMapper.addLiveRoomInfo(liveInfo);
        log.info("id：{}", liveInfo.getId());
        String liveRoomKey = Constant.REDIS_ROOM_KEY_PREFIX + liveInfo.getId();


        // 将直播间信息存储到 Redis
        Map<String, String> roomInfo = new HashMap<>();
        roomInfo.put("userId", userId);
        roomInfo.put("title", title);
        roomInfo.put("pushUrl", pushUrl);
        roomInfo.put("pullUrl", pullUrl);
        roomInfo.put("roomId", liveInfo.getId().toString());

        //封面上传到阿里云oss
        if (coverImage != null) {
            String fileName = coverImage.getOriginalFilename();
            String uploadFile = aliyunOSSUtil.uploadFile(coverImage, fileName);
            System.out.println("uploadFile = " + uploadFile);

            roomInfo.put("cover", uploadFile);
        }else {
            roomInfo.put("cover", "https://cy-dy-live.oss-cn-shenzhen.aliyuncs.com/%7B08F7BD55-CF9B-E153-E478-FC2E9DAF2950%7D.jpg");
        }


        // 使用 HASH 存储直播间信息
        MyRedisTemplate.opsForHash().putAll(liveRoomKey, roomInfo);

        // 设置过期时间为一天
        MyRedisTemplate.expire(liveRoomKey, 1, TimeUnit.DAYS);

        // 返回直播间播放地址
        return RestBean.success("创建直播间成功", roomInfo);
    }

    @Override
    public RestBean<ArrayList<LiveInfo>> getAllLiveInfo() {
        ArrayList<LiveInfo> liveInfos = new ArrayList<>();
        Set<String> keys = MyRedisTemplate.keys(Constant.REDIS_ROOM_KEY_PREFIX+"*");
        if (keys == null) return RestBean.success("直播间不存在");
        for (String key : keys) {

            Map<Object, Object> roomInfo = MyRedisTemplate.opsForHash().entries(key);

            //转成对象

            LiveInfo liveRoomInfo = new LiveInfo();

            liveRoomInfo.setUserId((String) roomInfo.get("userId"));

            liveRoomInfo.setTitle((String) roomInfo.get("title"));

            liveRoomInfo.setPullUrl((String) roomInfo.get("pullUrl"));

            liveRoomInfo.setPushUrl((String) roomInfo.get("pushUrl"));

            liveRoomInfo.setCover((String) roomInfo.get("cover"));

            liveRoomInfo.setRoomId((String) roomInfo.get("roomId"));

            liveInfos.add(liveRoomInfo);

            log.info("liveRoomInfo = {}", liveRoomInfo);
        }

        return RestBean.success("获取所有直播间信息成功", liveInfos);
    }

    @Override
    public RestBean<String> stopLive(String roomId) {

        String liveRoomKey = Constant.REDIS_ROOM_KEY_PREFIX + roomId;
        log.info(liveRoomKey);
        if (Boolean.TRUE.equals(MyRedisTemplate.hasKey(liveRoomKey))) {
            MyRedisTemplate.delete(liveRoomKey);
            return RestBean.success("停止直播成功");
        } else
            return RestBean.failure(400,"直播间不存在");
    }

    @Override
    public RestBean getAllLive() {
        return liveUtil.getAllLive();
    }

    //封禁streamName对应直播流

    @Override
    public RestBean banStream(String streamName, String BannedDuration) {
        return liveUtil.banStream(streamName, BannedDuration);
    }
}
